package org.iteam.bank.mina.client;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.iteam.bank.mina.utils.ConfigLoader;
import org.iteam.mina.Constant;
import org.iteam.mina.codec.MessageCodecFactory;
import org.iteam.mina.filter.ClientKeepAliveFilterInMina;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IoSessionFactory {
	private final String IP = ConfigLoader.get("gsp.ip");
	private final int PORT = Integer.valueOf(ConfigLoader.get("gsp.port"));
	private final Long timeoutMillis = Long.valueOf(ConfigLoader.get("gsp.timeoutMillis"));
	/****** 通用AES密匙 ******/
	public static final String KEY_AES = ConfigLoader.get("gsp.KEY_AES");
	/****** 通用HMAC密匙 ******/
	public static final String KEY_HMAC = ConfigLoader.get("gsp.KEY_HMAC");

	private static NioSocketConnector connector = null;
	private static final Logger log = LoggerFactory.getLogger(MinaClientHandler.class);

	public static IoSessionFactory getInstance() {
		return Subclass.service;
	}

	private static final class Subclass {
		public static final IoSessionFactory service = new IoSessionFactory();
	}

	private IoSessionFactory() {
		super();
		try {
			connector = new NioSocketConnector();
			DefaultIoFilterChainBuilder chain = connector.getFilterChain();
			chain.addLast("keep-alive", new ClientKeepAliveFilterInMina());// 心跳
			chain.addLast("logger", new LoggingFilter(MinaClientHandler.class));
			chain.addLast("codec", new ProtocolCodecFilter(new MessageCodecFactory(Constant.UTF_8)));
			// 取消设置Handler 并 启用 IoSession.read()
			connector.getSessionConfig().setUseReadOperation(true);
			connector.setHandler(new MinaClientHandler());
			connector.setConnectTimeoutMillis(Constant.CONNECT_TIMEOUT_MILLIS);
			connector.getSessionConfig().setReadBufferSize(Constant.READ_BUFFER_SIZE);// 发送缓冲区10M
			connector.getSessionConfig().setReceiveBufferSize(Constant.RECEIVE_BUFFER_SIZE);// 接收缓冲区10M

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	/**
	 * 获取session连接
	 * 
	 * @return
	 */
	public IoSessionConn getSession() {
		IoSessionConn pool = null;
		pool = new IoSessionConn(IP, PORT, connector, timeoutMillis);
		pool.conn();
		return pool;
	}

	public IoSessionConn getSession(String ip, Integer prot) {
		IoSessionConn pool = null;
		pool = new IoSessionConn(ip, prot, connector, timeoutMillis);
		pool.conn();
		return pool;
	}

	/**
	 * session 连接归次
	 * 
	 * @param pool
	 */
	public void releaseSession(IoSessionConn pool) {
		pool.close();
	}

}
